"""
word 转pdf  电脑需要提前安装office
"""
import os
from win32com import client
import fitz
from PIL import Image


def get_path():
    path = os.getcwd()
    filename_list = os.listdir(path)
    pdfdir = os.path.join(path, "jpg")
    # 当前目录下生产pdf文件夹
    if not os.path.exists(pdfdir):
        os.makedirs(pdfdir)

    wordname_list = [
        filename for filename in filename_list if filename.endswith((".doc", ".docx"))]

    for wordname in wordname_list:
        pdfname = os.path.splitext(wordname)[0] + ".pdf"
        # 拼接 路径和文件名
        wordpath = os.path.join(path, wordname)
        pdfpath = os.path.join(pdfdir, pdfname)
        # yield 生成器
        yield wordpath, pdfpath


def convert_word_to_pdf():
    word = client.Dispatch("Word.Application")
    word.Visible = 0
    for wordpath, pdfpath in get_path():
        print(">>:", wordpath, "开始转换pdf...")
        newpdf = word.Documents.Open(wordpath)
        newpdf.SaveAs(pdfpath, FileFormat=17)
        newpdf.Close()
        print(">>:", wordpath, "已完成pdf转换")


def conver_to_picture():
    path = os.getcwd()
    pdf_path = os.path.join(path, "jpg")
    filename_list = os.listdir(pdf_path)

    pdfname_list = [
        filename for filename in filename_list if filename.endswith((".pdf", ".PDF"))]
    for pdfname in pdfname_list:
        pdf_to_picture(pdf_path, pdfname)


def pdf_to_picture(path, pdfname):
    pdfpath = os.path.join(path, pdfname)
    pdfDoc = fitz.open(pdfpath)
    pdf_pure_name = os.path.splitext(pdfname)[0]
    print("-------pdf %s 开始转换成png--------" % pdfname)
    for pg in range(pdfDoc.page_count):
        page = pdfDoc[pg]
        rotate = int(0)
        zoom_x = 2.5
        zoom_y = 2.5
        mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
        pix = page.get_pixmap(matrix=mat, alpha=False)

        imgpath = os.path.join(path, pdf_pure_name + "-" + str(pg + 1) + ".png")
        pix._writeIMG(imgpath, 1)
        print("-------%s 完成--------" % (pdf_pure_name + "-" + str(pg + 1) + ".png"))
    pdfDoc.close()
    # 删除pdf
    os.remove(pdfpath)


def get_png_path():
    pngdir = os.path.join(os.getcwd(), "jpg")
    filename_list = os.listdir(pngdir)
    jpgname_list = [
        filename for filename in filename_list if filename.endswith((".png", ".PNG"))]

    for jpgname in jpgname_list:
        pngname = os.path.splitext(jpgname)[0] + ".jpg"
        # 拼接 路径和文件名
        jpgpath = os.path.join(pngdir, jpgname)
        pngpath = os.path.join(pngdir, pngname)
        # yield 生成器
        yield jpgpath, pngpath


def convert_png():
    for jpgpath, pngpath in get_png_path():
        try:
            im = Image.open(jpgpath)
            im.save(pngpath)
            os.remove(jpgpath)
            print(jpgpath + "-->转换完成")
        except Exception as e:
            print(e)


if __name__ == "__main__":
    convert_word_to_pdf()
    conver_to_picture()
    convert_png()
    print("========全部完成========")
